package com.lagou.rpc.consumer.proxy;

import com.alibaba.fastjson.JSON;
import com.lagou.rpc.common.RpcRequest;
import com.lagou.rpc.common.RpcResponse;
import com.lagou.rpc.consumer.ClientBootStrapApplication;
import com.lagou.rpc.consumer.client.RpcClient;
import lombok.Data;
import org.apache.curator.framework.CuratorFramework;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * 客户端代理类-创建代理对象
 * 1.封装request请求对象
 * 2.创建RpcClient对象
 * 3.发送消息
 * 4.返回结果
 */
@Component
@Data
@ConfigurationProperties(prefix = "rpc")
public class RpcClientProxy {

    private int requestCount = 0;

    public Object createProxy(Class serviceClass) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //1.封装request请求对象
                        RpcRequest rpcRequest = new RpcRequest();
                        rpcRequest.setRequestId(UUID.randomUUID().toString());
                        rpcRequest.setClassName(method.getDeclaringClass().getName());
                        rpcRequest.setMethodName(method.getName());
                        rpcRequest.setParameterTypes(method.getParameterTypes());
                        rpcRequest.setParameters(args);
                        //2.创建RpcClient对象
                        RpcClient rpcClient = null;
                        //获取负载服务地址
                        String s = getServer();
                        String[] server = s.split(":");
                        System.out.println("服务地址:" + Arrays.toString(server));
                        try {
                            rpcClient = new RpcClient(server[0], Integer.parseInt(server[1]));
                            System.out.println(s + "RPC客户端已创建!");
                        } catch (Exception exception) {
                            System.out.println("连接异常....");
                        }
                        try {
                            //3.发送消息
                            Object responseMsg = rpcClient.send(JSON.toJSONString(rpcRequest));
                            RpcResponse rpcResponse = JSON.parseObject(responseMsg.toString(), RpcResponse.class);
                            if (rpcResponse.getError() != null) {
                                throw new RuntimeException(rpcResponse.getError());
                            }
                            //4.返回结果
                            Object result = rpcResponse.getResult();
                            return JSON.parseObject(result.toString(), method.getReturnType());
                        } catch (Exception e) {
                            throw e;
                        } finally {
                            rpcClient.close();
                        }
                    }
                });
    }

    private String getServer() throws Exception {
        CuratorFramework client = ClientBootStrapApplication.getClient();
        List<String> serverList = client.getChildren().forPath(ClientBootStrapApplication.PATH);
        long lastTime = Long.MAX_VALUE;
        int serverIndex = -1;
        for (int i = 0; i < serverList.size(); i++) {
            String path = ClientBootStrapApplication.PATH + "/" + serverList.get(i);
            //数据内容
            byte[] bytes = client.getData().forPath(path);
            String time = new String(bytes);
            long timestamp = Long.parseLong(time);
            System.out.println("获取到的节点数据内容： " + timestamp);
            long l = System.currentTimeMillis() - timestamp;
            System.out.println("上一次请求时间差： " + l);
            if (l < 5000 && ((lastTime < timestamp) || (lastTime == Long.MAX_VALUE))) {
                lastTime = timestamp;
                serverIndex = i;
            }
        }
        if (serverIndex == -1) {
            serverIndex = new Random().nextInt(serverList.size());
            System.out.println("随机选择服务器：" + serverIndex);
        }
        return serverList.get(serverIndex);
    }
}
